package com.zhixinsou.wuyang.process;

import com.alibaba.fastjson.JSON;
import com.zhixinsou.wuyang.model.AnalysisReport;
import com.zhixinsou.wuyang.model.SheetModel;
import com.zhixinsou.wuyang.util.FileUtil;
import com.zhixinsou.wuyang.util.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProcessBuckingham {
    public static List<AnalysisReport> getAnalysisReportPageInfo(String filePath) {
        List<AnalysisReport> reports = new ArrayList<>();
        int startPage = 1;
        File file = new File(filePath);
        String[] lines = FileUtil.pdfReader(file, startPage, startPage).split("\r\n");
        Pattern pattern = Pattern.compile("([0-9]+)\\s-\\s([0-9]+)$");
        while (lines.length > 1 && lines[0].equals("Table of Contents")) {
            for (String line : lines) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    AnalysisReport report = new AnalysisReport();
                    report.setFilePath(filePath);
                    report.setFileName(file.getName());
                    report.setStartPage(Integer.parseInt(matcher.group(1)));
                    report.setEndPage(Integer.parseInt(matcher.group(2)));
                    report.setBrokerName("THEBUCKINGHAMRESEARCH GROUP.");

                    reports.add(report);
                }
            }

            startPage++;
            lines = FileUtil.pdfReader(filePath, startPage, startPage).split("\r\n");
        }
        return reports;
    }

    public static void getAnalysisReportDetail2003(AnalysisReport report) {
        getAnalysisReportDetail2003_internal(report);
    }

    public static void getAnalysisReportDetail2004(AnalysisReport report) {
        getAnalysisReportDetail2004_internal(report);
    }
    
    public static void getAnalysisReportDetail2003_internal(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(), false);
        String[] lines = content.split("\r\n");

        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+,\\s*[0-9]{4}");
        for (String line : lines) {
            Matcher matcherDate = patternDate.matcher(line.trim());
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("\\s+[0-9]{1}/[0-9]{1,2}/[0-9]{4}$");
            for (String line : lines) {
                Matcher matcherDate = patternDate.matcher(line.trim());
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER){1}\\s*[0-9]+,\\s*[0-9]{4}");
            for (String line : lines) {
                Matcher matcherDate = patternDate.matcher(line.trim());
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("(Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec|Sep){1}\\.\\s*[0-9]+,\\s*[0-9]{4}");
            for (String line : lines) {
                Matcher matcherDate = patternDate.matcher(line.trim());
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }
        
        Pattern patternCompanyName = Pattern.compile("([a-zA-Z0-9&\\s\\.,’]+)\\s*\\(([a-zA-Z]+).*\\)([^-–]*)");
        boolean nameFound = false;
        for (String line : lines) {
            if (line.contains("Important disclosure information") || line.contains("potential conflicts") 
                    || line.contains("Important  disclosure information") || line.contains("conflicts  of interest")
                    || line.contains("interest appear at") || line.contains("Group makes a market")
                    || line.contains("The Buckingham Research Group")) {
                continue;
            }
            
            Matcher matcherCompanyName = patternCompanyName.matcher(line.trim());
            if (!nameFound && matcherCompanyName.find()) {
                report.setCompanyName(matcherCompanyName.group(1));
                report.setTicker(matcherCompanyName.group(2));
                nameFound = true;

                if (!StringUtil.isEmpty(matcherCompanyName.group(3)) && !matcherCompanyName.group(3).trim().equals("*")) {
                    report.setRating(matcherCompanyName.group(3));
                    break;
                }
                continue;
            }

            if (nameFound) {
                report.setRating(line.trim());
                break;
            }
        }
        
        Pattern patternName = Pattern.compile("^([^\\(]+)[^@]+@");
        for (String line : lines) {
            Matcher matcherName = patternName.matcher(line.trim());
            while (matcherName.find()) {
                report.addAnalystName(matcherName.group(1));
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage());
        Pattern patternSentence = Pattern.compile("(.*household have a financial interest[\\s\\S]+?)((Yes|No){1})");
        Matcher matcher = patternSentence.matcher(content);
        while (matcher.find()) {
            report.addOwnershipDisclosure(matcher.group(1));
            report.addCompaniesMentioned(matcher.group(2));
        }

        System.out.println(JSON.toJSON(report));
    }

    public static void getAnalysisReportDetail2004_internal(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(), false);
        String[] lines = content.split("\r\n");

        int dateLine = 0;
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+,\\s*[0-9]{4}");
        for (String line : lines) {
            Matcher matcherDate = patternDate.matcher(line.trim());
            dateLine++;
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("\\s+[0-9]{1}/[0-9]{1,2}/[0-9]{4}$");
            dateLine = 0;
            for (String line : lines) {
                Matcher matcherDate = patternDate.matcher(line.trim());
                dateLine++;
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER){1}\\s*[0-9]+,\\s*[0-9]{4}");
            dateLine = 0;
            for (String line : lines) {
                dateLine++;
                Matcher matcherDate = patternDate.matcher(line.trim());
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }
        if (StringUtil.isEmpty(report.getDate())) {
            patternDate = Pattern.compile("(Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec|Sep){1}\\.\\s*[0-9]+,\\s*[0-9]{4}");
            dateLine = 0;
            for (String line : lines) {
                dateLine++;
                Matcher matcherDate = patternDate.matcher(line.trim());
                if (matcherDate.find()) {
                    report.setDate(matcherDate.group());
                    break;
                }
            }
        }

        Pattern patternCompanyName = Pattern.compile("([a-zA-Z0-9&\\s\\.,’]+)\\s*\\(([a-zA-Z]+).*\\)([^-–]*)");
        boolean nameFound = false;
        for (String line : lines) {
            Matcher matcher = patternCompanyName.matcher(line.trim());
            if (matcher.find()) {
                report.setCompanyName(matcher.group(1));
                report.setRating(matcher.group(2));
                nameFound = true;
                continue;
            }

            if (nameFound) {
                report.setRating(line.trim());
                break;
            }
        }
        /*
        Pattern patternCompanyName = Pattern.compile("([a-zA-Z0-9&\\s\\.,’]+)\\s*\\(([a-zA-Z]+).*\\)([^-–]*)");
        boolean nameFound = false;
        for (String line : lines) {
            if (line.contains("Important disclosure information") || line.contains("potential conflicts")
                    || line.contains("Important  disclosure information") || line.contains("conflicts  of interest")
                    || line.contains("interest appear at") || line.contains("Group makes a market")
                    || line.contains("The Buckingham Research Group")) {
                continue;
            }

            Matcher matcherCompanyName = patternCompanyName.matcher(line.trim());
            if (!nameFound && matcherCompanyName.find()) {
                report.setCompanyName(matcherCompanyName.group(1));
                report.setTicker(matcherCompanyName.group(2));
                nameFound = true;

                if (!StringUtil.isEmpty(matcherCompanyName.group(3)) && !matcherCompanyName.group(3).trim().equals("*")) {
                    report.setRating(matcherCompanyName.group(3));
                    break;
                }
                continue;
            }

            if (nameFound) {
                report.setRating(line.trim());
                break;
            }
        }
        */

        Pattern patternName = Pattern.compile("^([^\\(]+)[^@]+@");
        for (String line : lines) {
            Matcher matcherName = patternName.matcher(line.trim());
            while (matcherName.find()) {
                report.addAnalystName(matcherName.group(1));
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage());
        Pattern patternSentence = Pattern.compile("(.*household have a financial interest[\\s\\S]+?)((Yes|No){1})");
        Matcher matcher = patternSentence.matcher(content);
        while (matcher.find()) {
            report.addOwnershipDisclosure(matcher.group(1));
            report.addCompaniesMentioned(matcher.group(2));
        }

        System.out.println(JSON.toJSON(report));
    }
    
    public static void process3(String rootDir, String resultPath) {
        List<AnalysisReport> reports = new ArrayList<>();
        File[] Files = new File(rootDir).listFiles();
        for (File file : Files) {
            if(file.getName().endsWith(".pdf"))
                try {
                    reports.addAll(getAnalysisReportPageInfo(file.getPath()));
                } catch (Exception e) {
                    System.out.println(file.getName());
                    e.printStackTrace();
                    continue;
                }
        }

        //以下代码为写入excel
        List<String> headers = new ArrayList<>();
        headers.add("Date");
        headers.add("Broker name");
        headers.add("Analyst name");
        headers.add("Company name");
        headers.add("Ticker");
        headers.add("Exchange");
        headers.add("Rating");
        headers.add("Initiating Coverage");
        headers.add("Prior recommendation");
        headers.add("Ownership disclosure");
        headers.add("Companies Mentioned");
        headers.add("PDF file name");
        headers.add("StartPage");
        headers.add("EndPage");
        SheetModel sheetModel = FileUtil.makeSheet(resultPath, "result", headers);

        List<String[]> data = new ArrayList<>();
        for (AnalysisReport report : reports) {
            try {
                getAnalysisReportDetail2003(report);
            } catch (Exception e) {
                System.out.println(JSON.toJSON(report));
                e.printStackTrace();
                continue;
            }

            String[] line = new String[]{report.getDate(),
                    report.getBrokerName(),
                    JSON.toJSONString(report.getAnalystNames()),
                    report.getCompanyName(),
                    report.getTicker(),
                    report.getExchange(),
                    report.getRating(),
                    report.getInitiatingCoverage(),
                    report.getPriorRecommendation(),
                    JSON.toJSONString(report.getOwnershipDisclosures()),
                    JSON.toJSONString(report.getCompaniesMentioned()),
                    report.getFileName(),
                    report.getStartPage() + "",
                    report.getEndPage() + ""};
            data.add(line);
        }

        FileUtil.exportSheet(sheetModel.getSheet(), data);
        FileUtil.closeSheet(sheetModel);
        System.out.println("Success!");
    }

    public static void process4(String rootDir, String resultPath) {
        List<AnalysisReport> reports = new ArrayList<>();
        File[] Files = new File(rootDir).listFiles();
        for (File file : Files) {
            if(file.getName().endsWith(".pdf"))
                try {
                    reports.addAll(getAnalysisReportPageInfo(file.getPath()));
                } catch (Exception e) {
                    System.out.println(file.getName());
                    e.printStackTrace();
                    continue;
                }
        }

        //以下代码为写入excel
        List<String> headers = new ArrayList<>();
        headers.add("Date");
        headers.add("Broker name");
        headers.add("Analyst name");
        headers.add("Company name");
        headers.add("Ticker");
        headers.add("Exchange");
        headers.add("Rating");
        headers.add("Initiating Coverage");
        headers.add("Prior recommendation");
        headers.add("Ownership disclosure");
        headers.add("Companies Mentioned");
        headers.add("PDF file name");
        headers.add("StartPage");
        headers.add("EndPage");
        SheetModel sheetModel = FileUtil.makeSheet(resultPath, "result", headers);

        List<String[]> data = new ArrayList<>();
        for (AnalysisReport report : reports) {
            try {
                getAnalysisReportDetail2004(report);
            } catch (Exception e) {
                System.out.println(JSON.toJSON(report));
                e.printStackTrace();
                continue;
            }

            String[] line = new String[]{report.getDate(),
                    report.getBrokerName(),
                    JSON.toJSONString(report.getAnalystNames()),
                    report.getCompanyName(),
                    report.getTicker(),
                    report.getExchange(),
                    report.getRating(),
                    report.getInitiatingCoverage(),
                    report.getPriorRecommendation(),
                    JSON.toJSONString(report.getOwnershipDisclosures()),
                    JSON.toJSONString(report.getCompaniesMentioned()),
                    report.getFileName(),
                    report.getStartPage() + "",
                    report.getEndPage() + ""};
            data.add(line);
        }

        FileUtil.exportSheet(sheetModel.getSheet(), data);
        FileUtil.closeSheet(sheetModel);
        System.out.println("Success!");
    }
}
